import Vue from 'vue'
import VueRouter from 'vue-router'

const Login = () => import('@/views/Login')
const Home = () => import('@/views/Home')
const Welcome = () => import('@/views/Welcome')
const Users = () => import('@/views/Users')
const Rights = () => import('@/views/Rights')
const Roles = () => import('@/views/Roles')
const Categories = () => import('@/views/Categories')
const Params = () => import('@/views/Params')
const Goods = () => import('@/views/Goods')
const Add = () => import('@/views/goods/Add')
const Orders = () => import('@/views/Orders')

Vue.use(VueRouter)

const routes = [
  {
    // 根目录 重定向到登录目录
    path: '/',
    redirect: '/home'
  }, {
    // 登录目录
    path: '/login',
    component: Login
  }, {
    // 首页目录，登录成功才能访问
    path: '/home',
    component: Home,
    redirect: "/welcome",
    children: [
      {path: '/welcome', component: Welcome},
      {path: '/users', component: Users},
      {path: '/roles', component: Roles},
      {path: '/rights', component: Rights},
      {path: '/categories', component: Categories},
      {path: '/params', component: Params},
      {path: '/goods', component: Goods},
      {path: '/goods/add', component: Add},
      {path: '/orders', component: Orders},
    ]
  }, {
    // 链接错误时处理，重定向到根目录
    path: '*',
    redirect: '/'
  }
]

const router = new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes
})

// 设置路由守卫
router.beforeEach((to, from, next) => {
  if (to.path === '/login')
    return next()
  // 获取本地isLogin状态，为1则已登录
  let login = localStorage.getItem('isLogin')
  if (login === '1') {
    next()
  }
  // 如果登录 直接跳转到相关页面
  else next('/login')
})

export default router
